#include "EventLoopThreadPool.h"
#include "EventLoopThread.h"
#include "EventLoop.h"

EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseLoop, const std::string &nameArg)
    : baseLoop_(baseLoop), name_(nameArg), started_(false), numThreads_(0), next_(0)
{
}
EventLoopThreadPool::~EventLoopThreadPool()
{
}

void EventLoopThreadPool::start(const ThreadInitCallback &cb)
{
    started_ = true;
    // 创建线程池
    for (int i = 0; i < numThreads_; i++)
    {
        char buff[name_.size() + 32] = {0};
        sprintf(buff, "%s%d", name_.c_str(), i);
        EventLoopThread *t = new EventLoopThread(cb, buff);
        // 储存线程和eventloop信息
        threads_.push_back(std::unique_ptr<EventLoopThread>(t));
        loops_.push_back(t->startLoop()); // 线程创建自己的栈上eventloop
    }
    if (numThreads_ == 0 && cb) // 只有主线程
    {
        cb(baseLoop_); // 线程初始化
    }
}
// 多线程中以轮询分配channel给subloop
EventLoop *EventLoopThreadPool::getNextLoop()
{
    EventLoop *loop = baseLoop_; // 只有主线程时返回
    if (!loops_.empty())
    {
        loop = loops_[next_];
        next_++;
        if (next_ >= loops_.size())
        {
            next_ = 0;
        }
    }
    return loop;
}

std::vector<EventLoop *> EventLoopThreadPool::getAllLoops()
{
    if (loops_.empty())
    {
        return std::vector<EventLoop *>(1, baseLoop_);
    }
    else
    {
        return loops_;
    }
}